package com.eques.service

import android.content.Context
import android.os.Handler
import android.util.Log
import com.eques.database.DevList
import com.eques.database.dao.DevListDao
import com.eques.event.EventTotalThread
import com.eques.https.ShaowUtils
import com.eques.icvss.api.ICVSSListener
import com.eques.icvss.core.module.user.Buddy
import com.eques.icvss.core.module.user.BuddyStatus
import com.eques.icvss.utils.ELog
import com.eques.icvss.utils.Method
import com.eques.util.AppUtils
import com.eques.util.BaseAppApplication
import com.eques.util.Config
import com.eques.util.EquesPreference
import com.eques.util.ObjIsEmptyUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.launch
import org.apache.commons.lang3.StringUtils
import org.greenrobot.eventbus.EventBus
import org.json.JSONException
import org.json.JSONObject
import kotlin.math.E

class ServerMessageResponse(private val ctx: Context, private val service: DoorBellService) :
    ICVSSListener {
    private val TAG = "ServerMessageResponse"
    private var equesPreference: EquesPreference? = null
    private var userToken: String? = null
    private lateinit var username: String
    private lateinit var ykDao: DevListDao
    private lateinit var fromBid: String

    init {
        initData()
    }

    private fun initData() {
        if (equesPreference == null) {
            equesPreference = EquesPreference(ctx.applicationContext)
        }
        username = equesPreference!!.getString(Config.EQUES_USER_NAME)!!
        ykDao = BaseAppApplication.instance!!.getYkDao(ctx)
    }

    override fun onDisconnect(i: Int) {}

    override fun onPingPong(code: Int) {
        ELog.i(TAG, " onPingPong..Code: ", code)
    }

    /**
     * 总线程事宜处理（所有操作返回）
     *
     * @param jsonObject // 总事物数据
     */
    override fun onMessageResponse(jsonObject: JSONObject) {
        ELog.i(TAG, " onMessageResponse() jsonObject msg： ", jsonObject.toString())

        val method = jsonObject.optString(Method.METHOD)
        fromBid = jsonObject.optString(Method.ATTR_FROM)
        if (StringUtils.isEmpty(method)) {
            ELog.d(TAG, " onMessageResponse method is null... ")
            return
        }
        when (method) {
            //用戶登录成功
            Method.METHOD_EQUES_SDK_LOGIN -> {
                loginResult(jsonObject)
            }

            //成功获取Token
            Method.METHOD_ALARM_GETOK -> {
                getTokenResult(jsonObject)
            }

            //成功获取设备列表
            Method.METHOD_BDYLIST -> {
                parseList(jsonObject)
            }

            //宠物设备详情
            Method.METHOD_WS1_DEVICEINFO -> {
                updateAnimalInfo(jsonObject)
            }

            //喂食结果
            Method.METHOD_SEND_ANIMAL_FOOD -> {
                animalFood(jsonObject)
            }

            //设备上下线
            Method.METHOD_DEVST -> {
                devst(jsonObject)
            }

            Method.METHOD_GET_COLONY -> {
                parServer(jsonObject)
            }

            Method.METHOD_PREVIEW -> {
                updateCallVisitorImg(jsonObject)
            }

            Method.METHOD_ADDBDY_RESULT->{
                DoorBellService.icvss!!.equesGetDeviceList()
            }


        }
    }


    /**
     * 门铃访客图片返回结果处理
     */
    private fun updateCallVisitorImg(jsonObject: JSONObject) {
        val fid = jsonObject.optString(Method.ATTR_ALARM_FID)
        val serviceContext = jsonObject.optString(Method.ATTR_ZIGBEE_CONTEXT)
        EventBus.getDefault()
            .post(EventTotalThread(Config.INCOMING_CALL_PREVIEW, fromBid, serviceContext, fid))

    }

    private fun parServer(jsonObject: JSONObject) {
        val code = jsonObject.optInt(Method.ATTR_ERROR_CODE)
        if (code == 0) {
            val colony: JSONObject = jsonObject.optJSONObject("colony")
            if (!ObjIsEmptyUtils.isEmpty(colony)) {
                val colony_id = colony.optInt("id")
                val colony_server = colony.optString("domain")
                equesPreference!!.putInt("colony_id", colony_id)
                equesPreference!!.putString("colony_server", colony_server)
            }
        }
    }

    /**
     * 处理动物喂食相关的JSON数据
     * 此函数主要用于解析传入的JSONObject对象，根据其中的字段来决定是否触发某些事件
     * 主要关注"reset"、"feed_state"和"meal_plan"这几个键的值
     *
     * @param jsonObject 包含动物喂食信息的JSON对象
     */
    private fun animalFood(jsonObject: JSONObject) {
        // 检查JSON对象中是否没有"reset"字段
        if (jsonObject.isNull("reset")) {
            // 如果没有"reset"字段，则检查"feed_state"字段是否存在
            if (!jsonObject.isNull("feed_state")) {
                // 获取"feed_state"字段的值
                val feed_state = jsonObject.optString("feed_state")
                // 如果"feed_state"的值为"doneing"，则发布一个事件表示喂食成功
                if ("doneing" == feed_state) {
                    EventBus.getDefault()
                        .postSticky(EventTotalThread(Config.EVENT_REFRESH_SEND_FOOD_SUCCES, 0))
                }
            }
            // 无论"feed_state"字段是否存在，都检查"meal_plan"字段是否存在
            if (!jsonObject.isNull("meal_plan")) {
                // 如果"meal_plan"字段存在，则发布一个事件表示喂食计划成功
                EventBus.getDefault()
                    .postSticky(EventTotalThread(Config.EVENT_REFRESH_SEND_FOOD_PLAN_SUCCES, 0))
            }
        }
    }

    /**
     * 更新宠物设备的详情
     *
     * @param jsonObject 包含宠物设备信息的JSON对象
     */
    private fun updateAnimalInfo(jsonObject: JSONObject) {
        // 打印宠物设备的详情信息
        ELog.d(TAG, "宠物设备的详情", jsonObject.toString())

        // 获取错误代码
        val code = jsonObject.optInt(Method.ATTR_ERROR_CODE)
        if (code == 0) {
            // 获取设备设置信息
            val dev = jsonObject.optJSONObject("setting")
            if (dev != null) {
                // 检查是否存在宠物喂食计划设置
                if (!dev.isNull("meal_plan")) { //宠物返回设置
                    try {
                        // 获取并打印宠物喂食计划
                        val meal_plan = dev.getString("meal_plan")
                        ELog.d(TAG, "宠物设备的详情计划:", meal_plan)

                        // 发送事件广播，更新喂食计划
                        EventBus.getDefault().post(
                            EventTotalThread(
                                Config.EVENT_REFRESH_GET_PLAN_SUCCES,
                                meal_plan
                            )
                        )
                    } catch (e: JSONException) {
                        // 如果解析错误，抛出运行时异常
                        throw RuntimeException(e)
                    }
                }
            }
        }
    }


    /**
     * 解析并处理门铃设备列表
     * 该函数从给定的JSONObject中提取门铃设备信息，并更新设备在线状态
     *
     * @param jsonObject 包含门铃设备列表信息的JSON对象
     */
    private fun parseList(jsonObject: JSONObject) {
//        CoroutineScope(Dispatchers.IO).launch {
//            ykDao.delete(username)
//        }
        val bdyList = jsonObject.optJSONArray("bdylist")
        if (bdyList != null) {
            for (i in 0 until bdyList.length() step 1) {
                val jsonBean = bdyList.getJSONObject(i)
                val devList = DevList();
                devList.username = username
                devList.is_share = jsonBean.optInt("is_share")
                devList.role = jsonBean.optInt("role")
                devList.speech = jsonBean.optInt("speech")
                devList.defaultNick = jsonBean.optString("defaultNick")
                devList.brandId = jsonBean.optInt("brandId")
                devList.name = jsonBean.optString("name")
                devList.bid = jsonBean.optString("bid")
                devList.nick = jsonBean.optString("nick")
                val flowList = ykDao.getBdyList(username, devList.bid)
                Log.e(
                    TAG,
                    "database 插入数据" + flowList.size + "==username=" + username + "==bid==" + devList.bid
                )
                if (flowList.size == 0) {
                    Log.e(TAG, "database 插入数据1")
                    ykDao.insertBdyList(devList)
                } else {
                    devList.id = flowList[0].id
                    Log.e(TAG, "database 更新数据2")
                    ykDao.updateBdyList(devList)
                }
            }
        }
        val onlines = jsonObject.optJSONArray("onlines")
        if (onlines != null) {
            for (k in 0 until onlines.length() step 1) {
                var jsonBean = onlines.getJSONObject(k)
                val uid = jsonBean.optString("uid")
                val stat = jsonBean.optInt("stat")
                val remoteupg = jsonBean.optInt("remoteupg")
                val bid = jsonBean.optString("bid")
                val status = jsonBean.optInt("status")
                val flowList = ykDao.getBdyList(username, bid)
                flowList.forEach {
                    if (bid.equals(it.bid)) {
                        it.stat = stat
                        it.status = status
                        it.remoteupg = remoteupg
                        it.uid = uid
                        ykDao.updateBdyList(it)
                        Log.e(TAG, "database 更新数据3")
                    }
                }
            }
        }
        EventBus.getDefault().post(EventTotalThread(Config.EVENT_BDY_LIST))

        CoroutineScope(Dispatchers.IO).launch {
            val listAll = ykDao.getUserBdyList(username)
            Log.e(TAG, "database 获取数据" + listAll.size)
            listAll.forEach { it ->
                Log.e(TAG, "database 获取数据")
                ShaowUtils.getInstance(ctx).getSetting(it.bid)
                ShaowUtils.getInstance(ctx).getState(it.bid)
            }
        }
//        Log.e(TAG, "setBuddy")
            setBuddy()
    }

    private fun setBuddy(){
        Log.e(TAG, "database 获取数据setBuddy" )
        CoroutineScope(Dispatchers.IO).launch {
            val listAll = ykDao.getUserBdyList(username)
            Log.e(TAG, "database 获取数据setBuddy" + listAll.size)
            listAll.forEach { info ->
                val buddy = Buddy()
                buddy.uid = info.uid
                buddy.bid = info.bid
                buddy.type = info.role
                buddy.nickname = info.nick
                buddy.name = info.name
                buddy.status = BuddyStatus.code(info.stat)
                buddy.remoteupg = info.remoteupg;
                Log.e(TAG, "database 获取数据setBuddy:$buddy")
                DoorBellService.icvss!!.setBuddy(buddy);
            }
        }

    }


    /**
     * 获取token
     *
     * @param jsonObject
     * @param getToken   // 是否获取token
     */
    private fun getTokenResult(jsonObject: JSONObject) {
        userToken = jsonObject.optString(Config.EQUES_USER_TOKEN)
        if (StringUtils.isBlank(userToken)) {
            ELog.d(TAG, " getTokenResult() userToken is null... ")
            return
        }
        equesPreference!!.putString(Config.EQUES_USER_TOKEN, userToken)
    }

    /**
     * 处理登录结果的函数
     *
     * @param jsonObject 包含登录结果信息的JSON对象
     * 该函数根据服务器返回的登录结果代码（code）来执行不同的操作
     * 主要处理四种情况：
     * 1. 登录成功（code为4000）
     * 2. 密码错误（code为4101）
     * 3. 用户不存在（code为4102）
     * 4. 用户名缺失（code为4103）
     */
    private fun loginResult(jsonObject: JSONObject) {
        val code = jsonObject.optInt("code")
        when (code) {
            4000 -> {//登录成功
                ELog.e(TAG, "login success")
                username = equesPreference!!.getString(Config.EQUES_USER_NAME)!!
                val uid = jsonObject.optString("uid")
                val bid = jsonObject.optString("bid")
                // 将登录信息保存到SharedPreferences中
                equesPreference!!.putString(Config.EQUES_USER_UID, uid)
                equesPreference!!.putString(Config.EQUES_USER_BID, bid)
                // 发送登录状态事件，通知其他组件
                EventBus.getDefault()
                    .post(EventTotalThread(Config.EVENT_LOGIN_STATE, username, uid, bid))

                // 获取token
                DoorBellService.icvss!!.getUserToken()
                // 获取设备列表
                DoorBellService.icvss!!.equesGetDeviceList()

                DoorBellService.icvss!!.getServers()
            }

            4101 -> {//密码错误
                ELog.e(TAG, "wrong password")
            }

            4102 -> {//用户不存在
                ELog.e(TAG, "not found user")
            }

            4103 -> {//用户名缺失
                ELog.e(TAG, "miss usename")
            }
        }
    }

    /**
     * 上下线消息
     */
    fun devst(jsonObject: JSONObject) {
        val bid = jsonObject.optString("bid")
        val stat = jsonObject.optInt("stat")
        CoroutineScope(Dispatchers.IO).launch {
            val flowList = ykDao.getBdyList(username, bid)
            flowList.forEach {
                if (bid.equals(it.bid)) {
                    it.stat = stat
                    ykDao.updateBdyList(it)
                    Log.e(TAG, "database 更新数据3")
                }
            }
            EventBus.getDefault()
                .post(EventTotalThread(Config.EVENT_DEVICE_LIST_REFRESH, bid, stat))

//            setBuddy()
        }

    }


}
